function loadBackups() {
    fetch('/get_backups')
        .then(response => response.json())
        .then(data => {
            const modal = document.getElementById('backup-modal');
            const list = document.getElementById('backup-list');
            
            if (list && modal) {
                list.innerHTML = data.backups.map(file => 
                    `<li onclick='restoreDatabase("${file}")'>${file}</li>`
                ).join('');
                modal.style.display = 'block';
            }
        })
        .catch(error => console.error('获取备份失败:', error));
}

// 暴露函数到全局作用域
window.loadBackups = loadBackups;

function restoreDatabase(backupFile) {
    if(confirm('确定要还原到此备份吗？当前数据将被覆盖！')) {
        fetch('/restore', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({backup_file: backupFile})
        })
        .then(response => response.json())
        .then(result => {
            alert(result.success ? '还原成功！' : '还原失败：' + result.message);
            document.getElementById('backup-modal').style.display = 'none';
        })
        .catch(error => alert('请求失败：' + error));
    }
}

document.addEventListener('DOMContentLoaded', function() {
    // 清空数据库按钮事件
    document.getElementById('clear-db-btn').addEventListener('click', function(e) {
    e.preventDefault();
    if (confirm('确定要清空数据库吗？该操作不可恢复！')) {
        fetch('/clear_database', { method: 'POST' })
            .then(response => response.json())
            .then(data => {
                if(data.success) {
                    alert('数据库已成功清空');
                    location.reload();
                } else {
                    alert('清空失败: ' + data.message);
                }
            })
            .catch(error => alert('请求异常: ' + error));
    }
}, {once: true});
    
    // 其他初始化代码
});

function showDatabaseStatus() {
    fetch('/database_status')
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP错误! 状态码: ${response.status}`);
        }
        return response.json();
      })
      .then(data => {
            const table = document.createElement('table');
            const thead = document.createElement('thead');
            const headerRow = document.createElement('tr');
            const headers = ['考试数量', '班级数量', '学生数量'];
            headers.forEach(headerText => {
                const th = document.createElement('th');
                th.textContent = headerText;
                headerRow.appendChild(th);
            });
            thead.appendChild(headerRow);
            table.appendChild(thead);

            const tbody = document.createElement('tbody');
            const row = document.createElement('tr');
            const cells = [data.data.exam_count, data.data.class_count, data.data.student_count];
            cells.forEach(cellText => {
                const td = document.createElement('td');
                td.textContent = cellText;
                row.appendChild(td);
            });
            tbody.appendChild(row);
            table.appendChild(tbody);

            const statusTableDiv = document.getElementById('database-status-table');
            statusTableDiv.style.display = 'block';
            statusTableDiv.innerHTML = '';
            statusTableDiv.appendChild(table);
        });
}

document.addEventListener('DOMContentLoaded', function() {
    document.querySelector('.import-link').addEventListener('click', handleImport);

document.querySelector('.status-link').addEventListener('click', function() {
    showDatabaseStatus();
    document.getElementById('content').style.display = 'none';
});
    document.querySelector('.query-link').addEventListener('click', function() {
    showAllStudents();
    document.getElementById('content').style.display = 'block';
});
    const statusTableDiv = document.getElementById('database-status-table');
    statusTableDiv.style.display = 'none';
});
// 显示班级配置界面
function showClassConfig() {
    document.getElementById('class-config').style.display = 'block';
    document.getElementById('content').style.display = 'none';
    
    fetch('/get_classes')
        .then(response => response.json())
        .then(data => {
            if(data.success) {
                const classList = document.getElementById('class-list');
                classList.innerHTML = data.classes.map(cls => 
                    `<label style=\"display: block; margin: 5px 0;\">
                        <input type=\"checkbox\" value=\"${cls}\"> ${cls}
                    </label>`
                ).join('');
            }
        });
}

// 保存选中班级配置
function saveChoosedClasses() {
    const checked = Array.from(document.querySelectorAll('#class-list input:checked'))
        .map(checkbox => checkbox.value);
    
    fetch('/save_choosed_classes', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({classes: checked})
    })
    .then(response => response.json())
    .then(result => {
        alert(result.success ? '保存成功！' : '保存失败：' + result.message);
        if(result.success) {
            document.getElementById('class-config').style.display = 'none';
        }
    });
}

// 暴露到全局作用域
window.showDatabaseStatus = showDatabaseStatus;
window.showClassConfig = showClassConfig;
window.saveChoosedClasses = saveChoosedClasses;

// 全局文件输入变量
let fileInput = null;

async function handleImport() {
    try {
        if (!fileInput) {
            fileInput = document.createElement('input');
            fileInput.type = 'file';
            fileInput.accept = '.csv, .xls, .xlsx';
            fileInput.addEventListener('change', handleFileSelect);
        }
        fileInput.click();
    } catch (error) {
        alert(`网络错误: ${error.message}`);
    }
}

async function handleFileSelect(event) {
    const file = event.target.files[0];
    if (file) {
        const formData = new FormData();
        formData.append('file', file);
        const response = await fetch('/import_scores', {
            method: 'POST',
            body: formData
        });
        const result = await response.json();
        if(result.success) {
            alert(result.message);
            showAllScores();
        } else {
            alert(`导入失败: ${result.message}`);
        }
    }
}

document.addEventListener('DOMContentLoaded', function() {
    // 加载下拉选项
    Promise.all([
        fetch('/get_all_grades').then(r => r.json()),
        fetch('/get_all_exams').then(r => r.json()),
        fetch('/get_all_classes').then(r => r.json())
    ]).then(([grades, exams, classes]) => {
        populateSelect('#gradeSelect', grades);
        populateSelect('#examSelect', exams);
        populateSelect('#classSelect', classes);
    });

    // 条件查询菜单点击事件
    document.getElementById('conditionalQueryMenu').addEventListener('click', function() {
        document.getElementById('queryForm').style.display = 'block';
        document.getElementById('content').innerHTML = '';
    });

    // 查询按钮点击事件
    document.getElementById('searchButton').addEventListener('click', function() {
        const params = {
            grade: document.getElementById('gradeSelect').value,
            exam_id: document.getElementById('examSelect').value,
            class_id: document.getElementById('classSelect').value,
            name: document.getElementById('nameInput').value
        };

        fetch('/search', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(params)
        })
        .then(response => response.json())
        .then(data => renderResults(data));
    });
});

function populateSelect(selector, items) {
    const select = document.querySelector(selector);
    items.forEach(item => {
        const option = document.createElement('option');
        option.value = item;
        option.textContent = item;
        select.appendChild(option);
    });
}

function renderResults(data) {
    const tableHtml = `<table class="table table-striped">
        <thead><tr>
            <th>年级</th><th>考试ID</th><th>班级</th>
            <th>学号</th><th>姓名</th><th>生物成绩</th>
            <th>校排名</th><th>班排名</th>
        </tr></thead>
        <tbody>
            ${data.map(row => `<tr>
                <td>${row.grade}</td><td>${row.exam_id}</td><td>${row.class_id}</td>
                <td>${row.student_id}</td><td>${row.name}</td><td>${row.biology_score}</td>
                <td>${row.school_rank}</td><td>${row.class_rank}</td>
            </tr>`).join('')}
        </tbody>
    </table>`;
    document.getElementById('resultTable').innerHTML = tableHtml;
}
